(function () {
    function SeatController() {
        this.UserID = null;
        this.Stage = null;
        this.UserSeatID = null;
        this.Seats = {};
        this.SeatPanel = null;
        this._propsUserInfo = null;
        this.tableStatus = null;

        viewer.register("arena.start", this.start.bind(this));
        viewer.register("room::into", this.roomInto.bind(this));
        viewer.register("room::ready", this.userReady.bind(this));
        viewer.register("room::readyCancel", this.userCancelReady.bind(this));
        viewer.register("room::leaveTable", this.leaveRoom.bind(this));
        viewer.register("room::userInto", this.userEnter.bind(this));
        viewer.register("room::userLeave", this.userLeave.bind(this));
        viewer.register("game::started", this.gameStart.bind(this));
        viewer.register("game::confirm", this.readyCompare.bind(this));
        viewer.register("game::waiting", this.gameWaiting.bind(this));
        viewer.register("user::chargeMoney", this.chargeMoney.bind(this));
        viewer.register("user::ticket", this.gameTicket.bind(this));
        viewer.register("chat::send", this.chatText.bind(this));
        viewer.register("chat::expressionSend", this.chatEmotion.bind(this));
        viewer.register("user::getGameCount", this.showProp.bind(this));
        viewer.register("prop::use", this.useProp.bind(this));
    }
    var _proto = SeatController.prototype;
    /**
     * @privite
     * 更新座位信息
     * 
     * @param players {object} 用户列表
     */
    _proto.updateSeats = function (players) {
        var Seats = this.Seats;
        var UserID = this.UserID;
        var SeatPanel = this.SeatPanel;
        var self = this;

        for(var i in players){
            var player = players[i];
            var position = player.position;
            var seat = SeatPanel.getChildByName("Seat." + position);

            seat.situp();
            seat.clickHandler = new Laya.Handler(seat, function () {
                if(!this._player || self.UserID == this._player.uid){return;}
                self._propsUserInfo = this._player;
                viewer.publish("io.emit", {
                    cmd : "user::getGameCount",
                    params : {
                        userId : this._player.uid
                    }
                });
            });

            if(player.uid != 0){
                seat.sitdown(player);
                switch(player.gameStatus | 0){
                    case 1:
                        seat.status = "cancel";
                        break;
                    case 2:
                        seat.status = "ready";
                        break;
                    case 3:
                    case 4:
                    case 5:
                        seat.status = "gaming";
                        break;
                    default:
                        seat.status = "empty";
                }
                if(player.uid == UserID){
                    this.UserSeatID = position;
                }
                utils.log(player.uid, UserID, this.UserSeatID);
            }
            Seats[position] = seat;
        }
    }
    /**
     * @privite
     * 变换座位位置
     * 把当前用户变换为3号座位
     */
    _proto.translateSeats = function () {
        utils.log("===-----------变换座位-----------===");
        var total  = 4;
        var offset = 3 - this.UserSeatID;
        var Seats = this.Seats;
        
        for(var i = 0; i < total; i ++){
            var pindex = i + 1;
            var _seat = Seats[pindex];

            if(offset > 0){
                pindex = pindex + offset > total ? pindex + offset - total : pindex + offset;
            }else{
                pindex = pindex + offset < 1 ? total + pindex + offset : pindex + offset;
            }
            
            utils.log("调整后的SeatId:" + pindex);
            _seat.position = pindex;
        }
    }
    /**
     * @privite
     * 初始化用户座位信息
     * 如果用户在游戏时刷新界面，需要重新初始化用户座位。如果用户在理牌中，需要重新发牌，如果已经理完牌，需要设置理牌状态为已理牌
     * 
     * @param {Array} playerList 用户信息
     */
    _proto.initSeatInfo = function (playerList, results) {
        var Seats = this.Seats;
        for(var i in playerList){
            if(playerList[i].uid == 0){continue;}
            var player = playerList[i];
            var seat   = Seats[player.position];
            var status = player.gameStatus | 0;

            switch(status){
                case 3:
                case 4:
                    switch(player.opstatus | 0){
                        case 0:
                            seat.dealCards(false);
                            break;
                        case 1:
                            seat.dealCards(false);
                            seat.readyCompare(!!player.sp);
                            break;
                    }
                    break;
                case 5:
                    utils.log("游戏正在比牌中，直接显示游戏结果");
                    utils.log(results);
                    
                    if(!results || !results[i]){
                        continue;
                    }
                    var cards = results[i].poker[0].cardArr.concat(results[i].poker[1].cardArr.concat(results[i].poker[2].cardArr));
                    
                    seat.dealCards(false);
                    seat.readyCompare(null, cards);
                    break;
            }
        }
    }

    /**
     * @public
     * 接收user::getGameCount消息，获取到用户游戏局数，并显示道具弹窗
     * 
     * @param res {object} 用户游戏局数
     */
    _proto.showProp = function (res) {
        if(Arena.CurScene !== "room"){return;}
        var count = res.count;
        this._propsUserInfo.count = count;
        
        viewer.publish("alert.show", "props", this._propsUserInfo);
    }
    /**
     * @public
     * 接收prop::use消息，用户使用道具
     * 
     * @param res {object} 道具相关信息
     */
    _proto.useProp = function (res) {
        if(Arena.CurScene !== "room"){return;}
        
        var fromSeat = this.Seats[res.fromPosition];
        var toSeat   = this.Seats[res.toPosition];
        if(!toSeat){return;}

        var fromPoint = {x : fromSeat.x + 22, y : fromSeat.y + 20};
        var toPoint   = {x : toSeat.x + 22,   y : toSeat.y + 20};


        fromSeat.coin = res.amount;

        var prop = new Laya.Image();
        prop.anchorX = 0.5;
        prop.anchorY = 0.5;
        prop.loadImage(res.img, 0, 0, 104, 104, Laya.Handler.create(prop, function (from, to, stage) {
            this.x = from.x + 52;
            this.y = from.y + 52;

            stage.addChild(this);
            Laya.Tween.to(this, {x : to.x + 52, y : to.y + 52, rotation : 360}, 600, null, Laya.Handler.create(this, function () {
                Laya.timer.once(500, this, function () {
                    Laya.Tween.to(this, {alpha : 0}, 300, null, Laya.Handler.create(this, function () {
                        this.removeSelf();
                    }));
                });
            }));
        }, [fromPoint, toPoint, this.Stage]));

        fromSeat.chat("text", {content : res.description});
    }
    /**
     * @public
     * 接收chat::send消息，文字聊天
     * 
     * @param res {object} 聊天数据
     */
    _proto.chatText = function (res) {
        if(Arena.CurScene !== "room"){return;}
        var seat = this.Seats[res.position];
        
        seat.chat("text", res);
    }
    /**
     * @public
     * 接收chat::expressionSend消息，聊天表情
     * 
     * @param res {object} 聊天数据
     */
    _proto.chatEmotion = function (res) {
        if(Arena.CurScene !== "room"){return;}
        var seat = this.Seats[res.position];
        
        seat.chat("emotion", res);
    }
    /**
     * @public
     * 接收room::ready消息，用户已准备
     * 
     * @param res {object} 已准备的用户信息
     */
    _proto.userReady = function (res) {
        if(Arena.CurScene !== "room"){return;}
        var seat = this.Seats[res.position];
        
        seat.status = "ready";
    }
    /**
     * @public
     * 接收room::readyCancel消息，用户取消准备
     * 
     * @param res {object} 取消准备的用户信息
     */
    _proto.userCancelReady = function (res) {
        if(Arena.CurScene !== "room"){return;}
        var seat = this.Seats[res.position];
        
        seat.status = "cancel";
    }
    /**
     * @public
     * 接收room::userInto消息，用户入桌
     * 
     * @param user {object} 玩家信息
     */
    _proto.userEnter = function (user) {
        if(Arena.CurScene !== "room"){return;}
        var seat =this.Seats[user.position];
        seat.sitdown(user);
    }
    /**
     * @public
     * 接收room::userLeave消息，用户离开
     * 
     * @param user {object} 玩家信息
     */
    _proto.userLeave = function (user) {
        if(Arena.CurScene !== "room"){return;}
        
        var seat =this.Seats[user.position];
        if(seat.status != "gaming"){
            seat.situp();
        }else{
            seat.status = "leaving";
        }
    }
    /**
     * @public
     * 接收room::leaveTable消息，重置变量
     */
    _proto.leaveRoom = function () {
        if(Arena.CurScene !== "room"){return;}

        // for(var i in this.Seats){
        //     this.Seats[i].empty();
        // }

        if(this.SeatPanel){
            this.SeatPanel.removeChildren();
        }

        this.Seats = {};
        this.UserSeatID = null;
        
        viewer.publish("alert.close");
    }
    /**
     * @public
     * 接收game::started消息，游戏开始
     */
    _proto.gameStart = function (res) {
        if(Arena.CurScene !== "room"){return;}
        var Seats = this.Seats;
        var positions = res.position;
        
        utils.log("game.start------>>");
        for(var item in positions){
            var position = positions[item];
        	var Seat = Seats[position];
        	
            Seat.status = "gaming";
            utils.log("position:" + position);
        	
            Seat.dealCards();
        }
        Laya.SoundManager.playSound("sound/start.mp3");
    }
    /**
     * @public
     * 接收game::confirm消息，用户理牌完成，准备比牌
     * 
     * @param res {object} 已完成理牌的用户信息
     */
    _proto.readyCompare = function (res) {
        if(Arena.CurScene !== "room"){return;}

        var position  = res.position;
        var Seat      = this.Seats[position];
        var special   = !!res.sp;

        Seat.readyCompare(special);
    }
    /**
     * @public
     * 接收game::waiting消息，游戏结束，等待开始
     * 
     * 清空座位的扑克牌
     */
    _proto.gameWaiting = function () {
        if(Arena.CurScene !== "room"){return;}
        var Seats = this.Seats;
        
        for(var i in Seats){
            var seat = Seats[i];

            if(seat.status == "ready" || seat.status == "cancel"){
                continue;
            }else if(seat.status == "leaving"){
                seat.situp();
                seat.status = "empty";
            }else{
                seat.reset();
                seat.status = "waiting";
            }
        }
    }
    /**
     * @public
     * 接收user::ticket消息，收取游戏服务费
     * 
     * @param {Object} res 服务费相关数据
     */
    _proto.gameTicket = function (res) {
        if(Arena.CurScene !== "room"){return;}
        var tipMsg = "收取门票：" + res.ticket;
        var ticketList = res.list;

        var Seats = this.Seats;
        for(var i in ticketList){
            Seats[i].coin = ticketList[i];
        }

        viewer.publish("alert.tip", tipMsg, 3000, 0.7);
    }
    /**
     * @public
     * 接收user::chargeMoney消息，为用户自动兑入游戏币
     * 
     * @param res {object} 自动兑入游戏币相关信息
     */
    _proto.chargeMoney = function (res) {
        if(Arena.CurScene !== "room"){return;}
        var takeinmoney = res.takeinmoney;
        var takeInMsg = "已为您自动兑入" + takeinmoney + "游戏币！";
        var position = null;

        if(res.position){
            position = res.position | 0;

            if(res.amount){
                this.Seats[position].coin = res.amount;
            }

            if(this.UserSeatID == position){
                viewer.publish("alert.tip", takeInMsg, 3000, 0.7);
            }
        }else{
            viewer.publish("alert.tip", takeInMsg, 3000, 0.7);
        }
        
        if(res.promptMsg){
            var param = {
                message : res.promptMsg.content,
                checkBox : { visible : true, checked : true},
                closeHandler : function (isChecked) {
                    if(isChecked){
                        viewer.publish("io.emit", {
                            cmd : "user::updatePomptMsg",
                            params : {
                                token : token,
                                rpcId : res.promptMsg.rpcId
                            }
                        });
                    }
                }
            };

            viewer.publish("alert.show", "normal", param);
        }
    }
    /**
     * @public
     * 接收room::into消息，更新座位信息
     *
     * @param res {object} res.list座位信息
     */
    _proto.roomInto = function (res) {
        if(Arena.CurScene !== "room"){return;}
        utils.log("SeatController.into");
        var playerList = res.list;

        this.tableStatus = res.tableStatus | 0;
        this.SeatPanel = this.Stage.getChildByName("seat.panel");
        
        this.updateSeats(playerList);
        setTimeout(this.translateSeats.bind(this), 0);
        setTimeout(this.initSeatInfo.bind(this, playerList, res.results), 0);
    }
    /**
     * @public
     * 游戏开始时监听arena.start消息，初始化相关变量
     */
    _proto.start = function () {
        this.Stage = Arena.Stage;
        this.UserID = Arena.UserID;
    }
    /**
     * @public
     * 游戏开始时监听arena.start消息，初始化相关变量
     */
    _proto.start = function () {
        this.Stage = Arena.Stage;
        this.UserID = Arena.UserID;
    }

    new SeatController();
})();